<template>
    <div class="shop-car pt15" >
        <div v-if="list&&list.length>0" class="plr15">
            <div class="item " :class="{mt15: i!=0}" v-for="(shop, i) in list" :key="i">
                <div class="shop ptb15 plr10" >
                    <div class="checkbox v-middle"><van-checkbox :data-index="i" checked-color="#e01212" :value="shop.checked" v-on:change="onChange($event,shop, 1)"></van-checkbox></div>
                    <img class="ml6 v-middle" src="/static/images/gwc_dianpu.png" alt="">
                    <span  @click="link2('/pages/project2/sjxq?id='+shop.id )" class="ml5 mr10 v-middle  f-bold">{{shop.name}}</span>
                    <van-icon @click="link2('/pages/project2/sjxq?id='+shop.id )" name="arrow v-middle" />
                </div>
                <div class=" bgc-fff8f8 plr10 pb10" v-for="(item, j) in shop.list" :key="j">
                    <div class="item-content">
                        <div class="check-box pt30 pr8">
                            <van-checkbox :data-index="j" checked-color="#e01212" :value="item.checked" v-on:change="onChange($event,item, 2)"></van-checkbox>
                        </div>
                        <div class="item-content_photo">
                            <img :src="item.cover">
                        </div>
                        <div class="item-content_text">
                            <div class="ellipsis_2 lh20 fs-15 pt2">{{item.name}}</div>
                            <div v-for="(cate,k ) in item.buySpecCate" :key="k" class="fs-13 lh12 pt6 c-999">{{cate.name}}：{{cate.child.name}}</div>
                            <!-- <div v-if="item.buySpecs.name" class="fs-13 lh12 pt6 c-999">规格：{{item.buySpecs.name}}</div> -->
                        </div>
                    </div>
                    <div class="tr pt10 pb10">
                        <span class="c-ff4444 fs-18 v-middle mr40">￥{{item.allPrice}}</span>
                        <div class="inline-block v-middle"><van-stepper :disable-input="true" :min="0" :button-size="22" :value="item.count" v-on:change="countChange($event,item)" /></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div v-else class="nodata tc">
            <img src="http://cdn.qiniu.yystec.com/gdmedia/gwc_zw.png" alt="">
            <div class="c-999 fs-13 pt20">购物车竟然是空的</div>
            <div class="btn mt20" @click="link('/pages/index/index')">去首页逛逛</div>
        </div>
        
        <div class="h50"></div>
        <div class="bot-bar" :class="{'bot-bar-2': type==2}">
            <div class="info pl17">
                <van-checkbox  checked-color="#e01212" v-on:change="selAll" :value="allChecked"><span class="c-666 fs-12">全选</span></van-checkbox>
            </div>
            <div class="right">
                <div class="c-666 fs-12">
                    合计: <span class="c-fe4646 mr10">￥{{allMoney}}</span>
                    <div class="btn" @click="toSubmit">结算({{count}})</div>
                </div>
            </div>
        </div>
        <NavBar :active="3" name="index3"></NavBar>
    </div>
</template>

<script>
import goodsApi from "@/api/api-product";
import orderApi from "@/api/api-order";
import _ from "underscore";
export default {
    name: "shopcar",
    props:['type'],
    components: {

    },
    data(){
        return {
            list: [],
            form: {

            },
            product: {},
            address: {},
            allChecked: false,
            checkList: [],
            count: 0,
            shopCar: [],
            allMoney: 0,
            loadInit: false,
            shopId: ""
        }
    },
    onLoad(options){
        this.shopId = options.shopId
        // this.loadInit = true
        this.init()
    },
    onShow(){
        this.init()
        wx.hideHomeButton()
    },
    mounted() {
        
    },
    methods: {
        init(){
            var shopCar = this.$store.getters.shopCar? JSON.parse(JSON.stringify(this.$store.getters.shopCar)) : []
            this.shopCar = shopCar
            var ids = []
            var shopCarJson = {}
            var shop = {}
            var shopIds = [], prdIds = []
            var disCount = 0, disMoney = 0
            
            if(wx.getStorageSync("buy-clear")!=1){
                wx.removeStorageSync("buy-clear")
                this.list.forEach(v => {
                    if(v.checked){
                        shopIds.push(v.id)
                    }
                    v.list.forEach(m => {
                        if(m.checked){
                            prdIds.push(m.prdId + ((m.buySpecs&&m.buySpecs.specId) || ""))
                            disCount += m.count
                            disMoney += m.price * m.count
                        }
                    })
                })
            }
            

            shopCar.forEach(v => {
                v.checked = prdIds.indexOf(v.prdId + ((v.buySpecs&&v.buySpecs.specId) || ""))!=-1
                v.allPrice = (v.price * v.count).toFixed(2)
                var tmp 
                if(!shop[v.shopId]){
                    tmp = []
                    shop[v.shopId] = tmp
                } else {
                    tmp = shop[v.shopId]
                }
                tmp.push(JSON.parse(JSON.stringify(v)))
            })
            var list = []
            for(var k in shop){
                var tmp = shop[k][0]
                list.push({
                    checked: shopIds.indexOf(k)!=-1,
                    id: tmp.shopId,
                    name: tmp.shop_name,
                    list: shop[k]
                })
            }
            this.list = list

            
            this.count = disCount
            this.allMoney = disMoney.toFixed(2)
        },
        ValidatePrds(ids, shopCar, shopCarJson){
            if(ids.length == 0){
                return
            }
            var vm = this
            orderApi.ValidatePrds({
                prdIds: ids
            }).then(res => {
                res.result.forEach(v => {
                    shopCarJson[v.prdId] = _.assign(shopCarJson[v.prdId], v)
                })
                var list = []
                for(var k in shopCarJson){
                    list.push(shopCarJson[k])
                }
                this.list = list
                this.saveChange()
            })
        },
        GetProduct(){
            var vm = this
            goodsApi.GetProduct({
                prdId: this.form.prdId
            }).then(res => {
                this.product = res.result
            })
        },
        del(i, checked){
            if(checked){
                this.count--
            }
            
            this.list.splice(i, 1)
            this.saveChange()
        },
        saveChange(item, del){
            if(del){
                this.shopCar.splice(this.shopCar.indexOf(item), 1)
            } else {
                var tmp
                for(var i=0; i<this.shopCar.length; i++){
                    tmp = this.shopCar[i]
                    if(tmp.prdId==item.prdId && JSON.stringify(tmp.buySpecs)==JSON.stringify(item.buySpecs)){
                        tmp.count = item.count
                        break;
                    }
                }
            }
            this.$store.dispatch('setShopCar', this.shopCar)
        },
        submit(){
            orderApi.Submit({
                addressId: this.address.addressId,
                prds: [this.form]
            }).then(res => {
                if(res.code == 0){
                    this.$toast("下单成功")
                    this.$router.replace({
                        path: "/personal/order"
                    })
                } else {
                    this.$toast("下单失败")
                }
            })
        },
        selAll(e){
            this.allChecked = e.mp.detail
            var count = 0, money = 0
            this.list.forEach(v => {
                v.checked = e.mp.detail
                v.list.forEach(m => {
                    m.checked = e.mp.detail
                    if(m.checked){
                        money += m.price * m.count
                        count += m.count
                    }
                });
            });
            this.count = e.mp.detail? count : 0
            this.allMoney = money.toFixed(2)
        },
        toSubmit(){
            var list = [], tmp
            this.list.forEach(v => {
                v.list.forEach(m => {
                    if(m.checked){
                        tmp = JSON.parse(JSON.stringify(m))
                        delete tmp['checked']
                        list.push(tmp)
                    }
                });
            });
            if(list.length==0){
                return
            }

            wx.setStorageSync("sc-buy-product", JSON.stringify(list))
            wx.navigateTo({
                url: "/pages/personal/order/add"
            })
        },
        onChange(e, item, type){
            item.checked = e.mp.detail
            if(type==1){
                //商家选择
                var disCount = 0, disMoney = 0
                item.list.forEach(v => {
                    if(e.mp.detail){
                        if(!v.checked){
                            disCount += v.count
                            disMoney += v.price * v.count
                        }
                    } else {
                        if(v.checked){
                            disCount -= v.count
                            disMoney -= v.price * v.count
                        }
                    }
                    v.checked = e.mp.detail
                })
                
                this.count += disCount
                this.allMoney =  parseFloat(this.allMoney) + disMoney
                
            } else {
                //选择商品
                var m = (item.price * item.count)
                this.allMoney = parseFloat(this.allMoney) + (e.mp.detail? m : -m)
                this.count += (e.mp.detail? item.count : -item.count)
            }
            this.allMoney = this.allMoney.toFixed(2)
        },
        countChange(e, item){
            var dis = e.mp.detail - item.count
            item.count = e.mp.detail
            item.allPrice = (item.price * item.count).toFixed(2)
            if(item.checked){
                this.count += dis
                this.allMoney = (parseFloat(this.allMoney) + (dis * item.price)).toFixed(2)
            }
            if(e.mp.detail==0){
                var delShop
                this.list.forEach((v,i) => {
                    var i = v.list.indexOf(item)
                    if(i!=-1){
                        if(v.list.length==1){
                            delShop = i
                        } else {
                            v.list.splice(i, 1)
                        }
                    }
                })
                if(delShop===0 || delShop){
                    this.list.splice(delShop, 1)
                }
            }
            this.saveChange(item, e.mp.detail==0)
        },
        link2(url){
            wx.navigateTo({
                url: url
            })
        },
        link(url){
            if(this.shopId){
                wx.redirectTo({
                    url: "/pages/project2/sjxq?id="+ (this.shopId||"")
                })
            } else {
                wx.redirectTo({
                    url: "/pages/index/index"
                })
            }
            
        }
    }
};
</script>
<style lang="scss" scope>
@import './css/shopCar.scss';
</style>
